package com.example.demo.Service;

import com.example.demo.Bean.RegionStats;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.tomcat.util.file.ConfigurationSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class DataService implements InitializingBean {

    private String dataUrl = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private List<RegionStats> list = new ArrayList<>();


    //每日早晨8点更新
    //@Scheduled(cron = "0 0 8 * * *")

    @Scheduled(cron = "${anxuan.updateTime}")
    public void getData() throws IOException {


        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(dataUrl))
                .headers(httpHeaders ->httpHeaders.add("User-Agent",
                        "Mozilla/5.8"))
                .build();

        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        //log.info("body Description:{}", body);

        Reader reader = new InputStreamReader(body.getInputStream());
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        for (CSVRecord record: records) {
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record.get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            list.add(regionStats);
            log.info("RegionStats:{}",regionStats);
        }




    }

    public List<RegionStats> list(){
        return list;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        getData();
    }
}
